import { useUserInfo } from '/@/stores/userInfo';

const stores = useUserInfo();

// Types for better type safety
interface DictItem {
	code: string | number;
	value: string;
	typeCode: string;
	langMessage?: string;
	tagType?: string;
}

/**
 * Get dictionary item by code
 * Used for table column display with el-tag
 * @example
 * <el-table-column prop="fieldName" label="Description" width="140">
 *     <template #default="scope">
 *         <el-tag :type="di('dictCode', scope.row.fieldName)?.tagType">
 *             [{{di("dictCode", scope.row.fieldName)?.code}}]
 *             {{di("dictCode", scope.row.fieldName)?.value}}
 *         </el-tag>
 *     </template>
 * </el-table-column>
 */
export function getDictDataItem(dicName: string, dicItemCode: string | number): DictItem | undefined {
	const dictList = stores.getDictDataByCode(dicName);
	return dictList.find((item: DictItem) => item.code === dicItemCode);
}

/**
 * Get dictionary value by label
 * @param dicName Dictionary type code
 * @param label Dictionary label
 */
export function getDictValByLabel(dicName: string, label: string): string | undefined {
	const dictList = stores.getDictDataByCode(dicName);
	return dictList.find((item: DictItem) => item.value === label)?.code?.toString();
}

/**
 * Get dictionary label by value
 * @param dicName Dictionary type code
 * @param value Dictionary value
 */
export function getDictLabelByVal(dicName: string, value: string | number): string | undefined {
	const dictList = stores.getDictDataByCode(dicName);
	return dictList.find((item: DictItem) => item.code === value)?.value;
}

/**
 * Get dictionary type
 * @param dicName Dictionary type code
 */
export function getDictType(dicName: string): DictItem[] {
	return stores.dictList[dicName] || [];
}

/**
 * Get dictionary data list
 * Used for select components
 * @example
 * <el-select v-model="form.field" clearable placeholder="Please select">
 *     <el-option
 *         v-for="(item, index) in dl('dictCode')"
 *         :key="index"
 *         :value="item.code"
 *         :label="`[${item.code}] ${item.value}`"
 *     />
 * </el-select>
 */
export function getDictDataList(dicName: string): DictItem[] {
	return stores.getDictDataByCode(dicName);
}

/**
 * Get dictionary data list with integer codes
 * Specifically for enums that use number codes
 */
export function getDictDataListInt(dicName: string): DictItem[] {
	const dictList = stores.getDictDataByCode(dicName);
	return dictList.map((item: DictItem) => ({
		...item,
		code: typeof item.code === 'string' ? parseInt(item.code, 10) : item.code,
	}));
}

// Common aliases for shorter syntax
export const di = getDictDataItem;
export const dl = getDictDataList;
